package com.gamemost.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;

import com.gamemost.entity.BookRecent;
import com.gamemost.entity.BookStand;
import com.gamemost.entity.JSONParser;
import com.gamemost.managers.ResourcesManager;
import com.gamemost.templestay.Config;
import com.gamemost.templestay.DownloadImageService;
import com.gamemost.templestay.R;

public class XMLProvider {
	public static void creatBookRecentXML(ArrayList<BookRecent> list)
			throws ParserConfigurationException, TransformerException,
			IllegalArgumentException, IllegalStateException, IOException {
		System.out.println("creat xml");
		XmlSerializer xmlSerializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		xmlSerializer.setOutput(writer);
		xmlSerializer.startDocument("UTF-8", true);
		xmlSerializer.startTag("", "bookrecent");
		for (int i = 0; i < list.size(); i++) {
			// open tag: <study>
			BookRecent book = list.get(i);
			xmlSerializer.startTag("", "book");
			xmlSerializer.attribute("", BookRecent.TAG_BOOK_ID, book.getId());
			xmlSerializer.attribute("", BookRecent.TAG_TITLE, book.getTitle());
			xmlSerializer.attribute("", BookRecent.TAG_BOOK_COVER,
					book.get(BookRecent.TAG_BOOK_COVER));
			xmlSerializer.attribute("", BookRecent.TAG_BOOK_URL, book.getUrl());			
			xmlSerializer.attribute("", BookRecent.TAG_BOOK_TYPE_ID, String.valueOf(book.getTypeBook()));
			String image = book.getImage();
			if (image == null)
				image = "no_book_cover.png";
			xmlSerializer.attribute("", "image", image);
			xmlSerializer.endTag("", "book");
		}
		xmlSerializer.endTag("", "bookrecent");
		xmlSerializer.endDocument();
		System.out.println(writer.toString());
		writeToFile(writer.toString(), "bookrecent.xml");
	}

	public static void creatBookStand(ArrayList<BookStand> list)
			throws IllegalArgumentException, IllegalStateException, IOException {
		System.out.println("creat xml");
		XmlSerializer xmlSerializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		xmlSerializer.setOutput(writer);
		xmlSerializer.startDocument("UTF-8", true);
		xmlSerializer.startTag("", "bookstand");
		for (int i = 0; i < list.size(); i++) {
			BookStand book = list.get(i);
			xmlSerializer.startTag("", "book");
			String id = book.get(BookStand.TAG_FOLDER_ID);
			if (id == null)
				id = "";
			String name = book.get(BookStand.TAG_FOLDER_NAME);
			if (name == null)
				name = "";
			xmlSerializer.attribute("", BookStand.TAG_FOLDER_ID, id);
			xmlSerializer.attribute("", BookStand.TAG_FOLDER_NAME, name);
			String image = book.getImage();
			if (image == null)
				image = "no_book_cover.png";
			xmlSerializer.attribute("", "image", image);

			xmlSerializer.endTag("", "book");
		}
		xmlSerializer.endTag("", "bookstand");
		xmlSerializer.endDocument();
		System.out.println(writer.toString());
		writeToFile(writer.toString(), "bookstand.xml");
	}

	public static void writeToFile(String data, String filename) {
		try {
			String p = Environment.getExternalStorageDirectory().toString();
			File f = new File(p + Config.DATA_APP + "/" + filename);
			OutputStream out = new FileOutputStream(p + Config.DATA_APP + "/"
					+ filename);
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out);
			outputStreamWriter.write(data);
			outputStreamWriter.close();
		} catch (IOException e) {
			Log.e("Exception", "File write failed: " + e.toString());
		}
	}

	public static void parseRecentXml(ArrayList<BookRecent> list)
			throws XmlPullParserException, IOException {
		InputStream in;
		in = new FileInputStream(Environment.getExternalStorageDirectory()
				.getPath() + Config.DATA_APP + "/bookrecent.xml");
		XmlPullParser parser = Xml.newPullParser();
		parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
		parser.setInput(in, null);
		parser.nextTag();
		parser.nextTag();int i = 0;
		while (!"bookrecent".equals(parser.getName())) {i++;
			System.out.println("inininin "+i);
			parser.nextTag();
			if (parser.getName().equals("book")) {
				BookRecent bookRecent = new BookRecent();
				String id = parser.getAttributeValue(null,
						BookRecent.TAG_BOOK_ID);
				String title = parser.getAttributeValue(null,
						BookRecent.TAG_TITLE);
				String bookcover = parser.getAttributeValue(null,
						BookRecent.TAG_BOOK_COVER);
				String image = parser.getAttributeValue(null, "image");
				String url = parser.getAttributeValue(null,
						BookRecent.TAG_BOOK_URL);
				String book_type = parser.getAttributeValue(null,
						BookRecent.TAG_BOOK_TYPE_ID);
				bookRecent.setTitle(title);
				bookRecent.setImage(image);
				bookRecent.setId(id);
				bookRecent.setBookcover(bookcover);
				bookRecent.setUrl(url);
				bookRecent.setTypeBook(Integer.parseInt(book_type));
				String imagePath = Environment.getExternalStorageDirectory()
						.toString()
						+ Config.IMAGE_BOOK
						+ "/"
						+ bookRecent.getImage();
				File f = new File(imagePath);
				Bitmap bitmap = null;
				if (f.exists()) {
					bitmap = DownloadImageService.decodeFile(f);
					bookRecent.setBitmap(Bitmap.createScaledBitmap(bitmap,
							2 * ResourcesManager.ac.width / 7,
							ResourcesManager.ac.height / 4, true));
				} else {
					Drawable drawable = ResourcesManager.ac.getResources()
							.getDrawable(R.drawable.no_book_cover);
					if (drawable instanceof BitmapDrawable) {
						bookRecent.setBitmap(Bitmap.createScaledBitmap(
								((BitmapDrawable) drawable).getBitmap(),
								2 * ResourcesManager.ac.width / 7,
								ResourcesManager.ac.height / 4, true));
					}
				}
				System.out
						.println(bookRecent.getId() + "=====================");
				if (JSONParser.checkExistBook(bookRecent) == -1) {
					list.add(bookRecent);
				}

			}
			parser.nextTag();
		}

	}

	public static void parseStandXml(ArrayList<BookStand> list)
			throws XmlPullParserException, IOException {
		InputStream in;
		in = new FileInputStream(Environment.getExternalStorageDirectory()
				.getPath() + Config.DATA_APP + "/bookstand.xml");
		XmlPullParser parser = Xml.newPullParser();
		parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
		parser.setInput(in, null);
		parser.nextTag();
		parser.nextTag();
		while (!"bookstand".equals(parser.getName())) {
			parser.nextTag();
			if (parser.getName().equals("book")) {
				BookStand bookStand = new BookStand();
				String id = parser.getAttributeValue(null,
						BookStand.TAG_FOLDER_ID);
				String title = parser.getAttributeValue(null,
						BookStand.TAG_FOLDER_NAME);
				String image = parser.getAttributeValue(null, "image");
				bookStand.setTitle(title);
				bookStand.setImage(image);
				bookStand.setId(id);

				String imagePath = Environment.getExternalStorageDirectory()
						.toString()
						+ Config.IMAGE_STAND
						+ "/"
						+ bookStand.getImage();
				File f = new File(imagePath);
				System.out.println(imagePath + " path book stand");
				Bitmap bitmap = null;
				if (f.exists()) {
					bitmap = DownloadImageService.decodeFile(f);
					bookStand.setBitmap(Bitmap.createScaledBitmap(bitmap,
							9 * ResourcesManager.ac.width / 20, 9 * 160
									* ResourcesManager.ac.width / (20 * 340),
							false));
				} else {
					Drawable drawable = ResourcesManager.ac.getResources()
							.getDrawable(R.drawable.no_img);
					if (drawable instanceof BitmapDrawable) {
						bookStand.setBitmap(Bitmap.createScaledBitmap(
								((BitmapDrawable) drawable).getBitmap(),
								9 * ResourcesManager.ac.width / 20, 9 * 160
										* ResourcesManager.ac.width
										/ (20 * 340), false));
					}
				}
				list.add(bookStand);
			}
			parser.nextTag();
		}
	}
}
